var express = require("express");
var router = express.Router();
// 引入依赖 验证码
global.require = require;
const SMSClient = require("@alicloud/sms-sdk");

let { listModel, userModel, clockModel, devModel } = require("../model/model");
/* GET home page. */

router.post("/add", function (req, res) {
  let { username, password } = req.body;

  res.send({
    code: 200,
  });
});

router.get("/list", async (req, res) => {
  let data = await listModel.find();
  res.send({ code: 200, data });
});

// 手机验证码发送  慎用 只有1000条
router.post("/yan", function (req, res) {
  let accessKeyId = "LTAI5t6F6WoyeFiS3Gjb6n27"; // AccessKey ID
  let secretAccessKey = "qiDN8E21FH6OI9Gahwo24SpNp2hYau"; // AccessKey Secret
  let signName = "liningyan"; // 签名名称
  let templateCode = "SMS_465403531"; // 短信模板code

  // 初始化sms_client
  const smsClient = new SMSClient({ accessKeyId, secretAccessKey });

  let phoneNum = "18830870933"; //手机号
  // 生成六位随机验证码
  let smsCode = Math.random().toString().slice(-6);
  console.log("smsCode:", smsCode);

  // 开始发送短信
  smsClient
    .sendSMS({
      PhoneNumbers: phoneNum,
      SignName: signName, //签名名称 前面提到要准备的
      TemplateCode: templateCode, //模版CODE  前面提到要准备的

      TemplateParam: `{"code":'${smsCode}'}`, // 短信模板变量对应的实际值，JSON格式
    })
    .then((result) => {
      console.log("result：", result);
      let { Code } = result;
      if (Code == "OK") {
        res.json({
          code: 0,
          msg: "success",
          sms: smsCode,
        });
        console.log("result:", result);
      }
    })
    .catch((err) => {
      console.log("报错：", err);
      res.json({
        code: 1,
        msg: "fail: " + err.data.Message,
      });
    });
});
//设备
router.get("/getDevice", async (req, res) => {
  let data = await devModel.find();
  res.send({ code: 200, data });
});
router.post("/addDevice", async (req, res) => {
  await devModel.create(req.body);
  res.send({ code: 200 });
});
//闹钟
router.get("/getClock", async (req, res) => {
  let data = await clockModel.find();
  res.send({ code: 200, data });
});
router.post("/addClock", async (req, res) => {
  await clockModel.create(req.body);
  res.send({ code: 200 });
});
module.exports = router;
